﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using static Marmat.Forms.Skin.SkinScrollControl;

namespace Marmat.Forms.Skin
{
    /// <summary>
    /// 卡片容器
    /// </summary>
    public partial class CardPanel : Panel
    {
        public CardPanel()
        {
            this.Buttons = new CardPanelCollection(this);
        }

        protected override void WndProc(ref Message m)
        {
            if (this._hideTitle)
            {
                base.WndProc(ref m);
                return;
            }
            var size = TextRenderer.MeasureText(this.Text, this.Font);
            switch (m.Msg)
            {
                case Win32API.Messages.WM_NCCALCSIZE:
                    // 处理非客户区
                    if (this.BorderStyle == BorderStyle.None)
                    {
                        RECT rect = (RECT)Marshal.PtrToStructure(m.LParam, typeof(RECT));
                        rect.Left += 1;
                        rect.Right -= 1;
                        rect.Bottom -= 1;
                        rect.Top += (size.Height + this.TitleMargin * 2) + 1;
                        //rect.Top += 50;
                        Marshal.StructureToPtr(rect, m.LParam, true); // 将修改完毕的区域拷贝给 lParam
                        m.Result = new IntPtr(1);
                    }
                    else
                        base.WndProc(ref m);
                    break;
                case Win32API.Messages.WM_NCLBUTTONDOWN://WM_NCHITTEST
                    var mousePoint = new Point((int)m.LParam);//鼠标位置（屏幕）
                    foreach (var recItme in rectangleDec)
                    {

                        //var p = this.RectangleToScreen(recItme.Value);
                        if (recItme.Value.Contains(this.PointToClient(mousePoint)))
                        {
                            this.clickItem = recItme.Key;
                            this.UpdateStyles();
                            return;
                        }
                    }
                    break;
                case 0xf:
                    base.WndProc(ref m);
                    ////拦截系统消息，获得当前控件进程以便重绘。
                    ////一些控件（如TextBox、Button等）是由系统进程绘制，重载OnPaint方法将不起作用.
                    ////所有这里并没有使用重载OnPaint方法绘制TextBox边框。
                    ////
                    ////MSDN:重写 OnPaint 将禁止修改所有控件的外观。
                    ////那些由 Windows 完成其所有绘图的控件（例如 Textbox）从不调用它们的 OnPaint 方法，
                    ////因此将永远不会使用自定义代码。请参见您要修改的特定控件的文档，
                    ////查看 OnPaint 方法是否可用。如果某个控件未将 OnPaint 作为成员方法列出，
                    ////则您无法通过重写此方法改变其外观。
                    ////
                    ////MSDN:要了解可用的 Message.Msg、Message.LParam 和 Message.WParam 值，
                    ////请参考位于 MSDN Library 中的 Platform SDK 文档参考。可在 Platform SDK（“Core SDK”一节）
                    ////下载中包含的 windows.h 头文件中找到实际常数值，该文件也可在 MSDN 上找到。

                    IntPtr hDC = Win32API.User32.GetWindowDC(m.HWnd);
                    if (hDC.ToInt32() == 0)
                        return;
                    System.Drawing.Graphics g = Graphics.FromHdc(hDC);
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

                    //绘制背景色
                    using (var bush = new SolidBrush(this.BackColor))
                        g.FillRectangle(bush, new Rectangle(0, 0, this.Width, this.Height));

                    //绘制标题
                    var rect_font = new Rectangle(10, this.TitleMargin, size.Width, size.Height);
                    TextRenderer.DrawText(g, this.Text, this.Font, rect_font, this.ForeColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);

                    //绘制边框
                    using (var pen = new Pen(this.BorderColor))
                    {
                        g.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
                        int y = this.TitleMargin * 2 + size.Height;
                        g.DrawLine(pen, 0, y, this.Width, y);
                    }
                    this.rectangleDec.Clear();
                    int x = this.Width - this.TitleMargin;
                    foreach (var item in this.Buttons)
                    {
                        var btn_size = TextRenderer.MeasureText(item.Text, this.Font);
                        var rect_btn = new Rectangle(x - btn_size.Width, this.TitleMargin, btn_size.Width, btn_size.Height);
                        var color = this.GetFouseColor(rect_btn, item);
                        TextRenderer.DrawText(g, item.Text, this.Font, rect_btn, color, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter);
                        x -= btn_size.Width + this.TitleMargin;
                        this.rectangleDec[item] = rect_btn;
                    }

                    //返回结果
                    m.Result = IntPtr.Zero;
                    //释放
                    Win32API.User32.ReleaseDC(m.HWnd.ToInt32(), hDC.ToInt32());
                    break;

                case Win32API.Messages.WM_NCMOUSEMOVE:
                    {

                    }

                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            point = e.Location;
            //this.Invalidate();
            base.OnMouseMove(e);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                foreach (var recItme in rectangleDec)
                {
                    if (recItme.Value.Contains(e.Location))
                    {
                        this.clickItem = recItme.Key;
                        this.UpdateStyles();
                        return;
                    }
                }
            }
            base.OnMouseDown(e);
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            this.clickItem = null;
            if (e.Button == MouseButtons.Left)
            {
                foreach (var recItme in rectangleDec)
                {
                    if (recItme.Value.Contains(e.Location))
                    {
                        //var args = new BreadcrumbArgs(recItme.Key);
                        //this.ItemClicked?.Invoke(this, args);
                        this.UpdateStyles();
                        return;
                    }
                }
            }
            base.OnMouseUp(e);
        }

        /// <summary>
        /// 获取焦点色
        /// </summary>
        /// <param name="rec"></param>
        /// <param name="item"></param>
        /// <returns></returns>
        private Color GetFouseColor(Rectangle rec, CardPanelItem item)
        {
            Color back_color = Configuration.DefaultTheme.Primary;
            if (!this.Enabled)
                back_color = this.ForeColor.Blend(Color.FromArgb(Convert.ToInt32(256 * 0.5), Color.White));
            else if (rec.Contains(point) && this.clickItem == item)
                back_color = back_color.Blend(Color.FromArgb(Convert.ToInt32(255 * 0.1), Color.Black));
            else if (rec.Contains(point))
                back_color = back_color.Blend(Color.FromArgb(Convert.ToInt32(255 * 0.2), Color.White));
            return back_color;
        }
    }
}
